package com.ee.chat.admin.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ee.chat.admin.service.IAuditService;
import com.ee.chat.admin.service.IOperationService;
import com.ee.chat.common.bean.Result;
import com.ee.chat.common.dao.*;
import com.ee.chat.common.entity.*;
import com.ee.chat.common.serconfig.MyAliOSSConfig;
import com.ee.chat.common.serconfig.MyNeteaseApp;
import com.ee.chat.common.service.IPushMessageService;
import com.ee.chat.common.service.IYieldService;
import com.ndhutu.ee.util.DateUtil;
import com.ndhutu.ee.util.StringUtil;
import com.ndhutu.ee.util.ali.oss.OSSUtil;
import com.ndhutu.ee.util.netease.im.IMUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author Shane
 * @Date 2019/10/7 21:20
 */
@Service
public class AuditServiceImpl implements IAuditService {
    @Resource
    UserAuditLogMapper userAuditLogMapper;
    @Resource
    UserLableLibMapper userLableLibMapper;
    @Resource
    HostLevelConfigMapper hostLevelConfigMapper;
    @Resource
    HostMapper hostMapper;
    @Resource
    UserLableMapper userLableMapper;
    @Resource
    HostPhotosMapper hostPhotosMapper;
    @Resource
    SysConfigMapper sysConfigMapper;
    @Resource
    IOperationService operationService;
    @Resource
    IPushMessageService pushMessageService;
    @Resource
    UserMapper userMapper;
    @Resource
    HostCallContentMapper hostCallContentMapper;
    @Resource
    HostTitleMapper hostTitleMapper;
    @Resource
    UserDynamicMapper userDynamicMapper;
    @Resource
    BaseMapper baseMapper;

    @Resource
    MyNeteaseApp app;
    @Resource
    IYieldService yieldService;
    @Resource
    MyAliOSSConfig aliOSSConfig;
    @Resource(name = "stringRedisTemplate")
    StringRedisTemplate redisTemplate;

    /**
     * 获取认证审核列表
     * @Author Shane
     * @Date 2019/10/7 21:21
     * @param
     * @return
     */
    @Override
    public Result authList(HttpServletRequest request, Integer page, Integer limit, Integer userId, Integer status, String time) throws Exception {
        Map<String, Object> data = new HashMap<>();

        if(StringUtil.isEmpty(time) && userId == null && status == null){
            HttpSession session = request.getSession(true);
            List<String> userPermissions = (List<String>)session.getAttribute("userPermissions");
            if(!userPermissions.contains("/audit/auth/viewList")){
                data.put("auths", new ArrayList<>());
                data.put("total", 0);

                return Result.returnSuccess(data);
            }
        }

        Date beginTime = null, endTime = null;
        if(!StringUtil.isEmpty(time)){
            String[] arr = time.split(" - ");
            beginTime = DateUtil.parse(arr[0]);
            endTime = DateUtil.parse(arr[1]);
        }

        Page<Map<String, Object>> p = new Page<>(page, limit);
        IPage<Map<String, Object>> iPage = userAuditLogMapper.list(p, userId, status, beginTime, endTime);
        List<Map<String, Object>> hostAudits = iPage.getRecords();
        for(Map<String, Object> hostAudit : hostAudits){
            //图片
            List<Map<String, Object>> potos = (List<Map<String, Object>>) JSONArray.parse(hostAudit.get("potos")+"");
            potos = potos == null ? new ArrayList<>() : potos;
            hostAudit.put("potos", potos);

            //处理标签
            List<Map<String, Object>> hostLables = new ArrayList<>();
            List<Integer> lables = JSONArray.parseArray(hostAudit.get("lables")+"", Integer.class);
            if(lables != null && lables.size() > 0){
                hostLables = userLableLibMapper.getUserLable(lables);
            }
            hostAudit.put("lables", hostLables);
        }

        data.put("auths", hostAudits);
        data.put("total", iPage.getTotal());

        operationService.addOperationLog(request, "查询认证列表数据");

        return Result.returnSuccess(data);
    }

    /**
     * 认证审核
     * @Author Shane
     * @Date 2019/10/10 0:49
     * @param
     * @return
     */
    @Override
    @Transactional
    public Result authAudit(HttpServletRequest request, Integer id, Integer status, Integer type, String reason) throws Exception {
        HttpSession session = request.getSession(true);
        AdminUser adminUser = (AdminUser)session.getAttribute("adminUser");
        Integer userId = adminUser.getId();

        UserAuditLog userAuditLog = userAuditLogMapper.selectById(id);
        if(userAuditLog.getStatus() != 0){
            return Result.returnFailure("该记录已经审核，不能重复审核");
        }

        //定义源文件
        List<String> files = new ArrayList<>();

        String ossUrl = "https://"+aliOSSConfig.getBucketName()+"."+aliOSSConfig.getEndpoint()+"/";

        Map<String, String> push = new HashMap<>();
        List<Map<String, Object>> potos = (List<Map<String, Object>>) JSONArray.parse(userAuditLog.getPotos());
        if(potos == null){
            potos = new ArrayList<>();
        }

        if(status == 1){    //通过
            User user = userMapper.selectById(userAuditLog.getUserId());

            //认证通过
            if(userAuditLog.getType() == 0){
                //添加主播信息
                HostLevelConfig hostLevelConfig = hostLevelConfigMapper.selectByLevel(0);
                Host host = new Host(userAuditLog.getUserId(),  hostLevelConfig.getId());
                hostMapper.insert(host);

                //添加主播标签
                userLableMapper.deleteByUserId(userAuditLog.getUserId());
                List<Integer> lableIds = JSONArray.parseArray(userAuditLog.getLables(), Integer.class);
                for(Integer lableId : lableIds){
                    UserLable userLable = new UserLable(userAuditLog.getUserId(), lableId);
                    userLableMapper.insert(userLable);
                }

                //添加招呼用语
                List<HostCallContent> hostCallContents = hostCallContentMapper.getSysCallContent();
                Iterator<HostCallContent> it = hostCallContents.iterator();
                while (it.hasNext()){
                    HostCallContent hostCallContent = it.next();
                    hostCallContent.setId(null);
                    hostCallContent.setUserId(user.getId());
                    hostCallContent.setCreateTime(null);
                    hostCallContent.setAuditTime(null);
                    hostCallContent.setAuditUserId(null);
                }
                for(HostCallContent hostCallContent : hostCallContents){
                    hostCallContentMapper.insert(hostCallContent);
                }

                operationService.addOperationLog(request, "审核通过"+ userAuditLog.getUserId()+"用户主播认证申请");

                push.put("title", "真人认证审核通过");
                push.put("content", "您提交的真人认证审核已经通过，感谢您的参与");

            }else if(userAuditLog.getType() == 1){
                operationService.addOperationLog(request, "审核通过"+ userAuditLog.getUserId()+"用户资料更新申请");

                push.put("title", "资料更新审核通过");
                push.put("content", "您提交的资料更新审核已经通过，请注意查看");

                if(!StringUtil.isEmpty(userAuditLog.getPotos())){
                    hostPhotosMapper.deleteByUserId(userAuditLog.getUserId());
                }
            }

            String icon = null;
            int isFirst = 0;
            for(Map<String, Object> poto : potos){
                if(icon == null && userAuditLog.getType() == 0){
                    icon = poto.get("icon")+"";
                    isFirst = Integer.parseInt(poto.get("isFirst")+"");
                }
                if(Integer.parseInt(poto.get("isFirst")+"") > isFirst && userAuditLog.getType() == 0){
                    icon = poto.get("icon")+"";
                }

                HostPhotos hostPhotos = new HostPhotos(userAuditLog.getUserId(), poto.get("icon")+"", Integer.parseInt(poto.get("isFirst")+""));
                hostPhotosMapper.insert(hostPhotos);
            }
            if(!StringUtil.isEmpty(userAuditLog.getIcon()) && userAuditLog.getType() == 1){
                icon = userAuditLog.getIcon();
            }

            //更新信息
            user.setIcon(icon);
            user.setName(userAuditLog.getName());
            user.setGender(userAuditLog.getGender());
            user.setPhone(userAuditLog.getPhone());
            user.setBirthday(userAuditLog.getBirthday());
            user.setHeight(userAuditLog.getHeight());
            user.setWeight(userAuditLog.getWeight());
            user.setUssId(userAuditLog.getUssId());
            user.setCityCode(userAuditLog.getCityCode());
            user.setProId(userAuditLog.getProId());
            user.setEmId(userAuditLog.getEmId());
            user.setPersionSign(userAuditLog.getPersionSign());
            userMapper.updateById(user);

            //IM更新
            IMUtil.updateUinfo(app.getIdPrefix()+userAuditLog.getUserId(), user.getName(), icon == null ? null : ossUrl+icon, user.getGender(), app);

            //更新审核记录
            userAuditLog.setStatus(status);

            //处理认证奖励
            if(userAuditLog.getType() == 0 && userAuditLog.getGender() == 0){
                yieldService.handleActivityYield(userAuditLog.getUserId(), userAuditLog.getId(), 1, userAuditLog.getCreateTime());
            }

        }else if(status == 2){  //拒绝
            userAuditLog.setStatus(status);
            userAuditLog.setReason(userAuditLog.getReason()==null ? reason : userAuditLog.getReason()+"\n"+reason);

            operationService.addOperationLog(request, "审核拒绝"+ userAuditLog.getUserId()+"用户主播认证/资料更新申请，理由："+reason);

            if(userAuditLog.getType() == 0){
                push.put("title", "真人认证审核驳回");
                push.put("content", "您提交的真人认证审核被驳回，原因：" + reason);
            }else{
                push.put("title", "资料更新审核驳回");
                push.put("content", "您提交的资料更新审核被驳回，原因：" + reason);
            }

            //获取源文件
            if(type == 1){
                if(!StringUtil.isEmpty(userAuditLog.getVideo())){
                    files.add(userAuditLog.getVideo());
                    userAuditLog.setVideo(null);
                }
                if(potos != null){
                    for(Map<String, Object> poto : potos){
                        files.add(poto.get("icon")+"");
                    }
                    userAuditLog.setPotos(null);
                }
                if(!StringUtil.isEmpty(userAuditLog.getIcon())){
                    files.add(userAuditLog.getIcon());
                    userAuditLog.setIcon(null);
                }
                if(!StringUtil.isEmpty(userAuditLog.getIdCardFront())){
                    files.add(userAuditLog.getIdCardFront());
                    userAuditLog.setIdCardFront(null);
                }
                if(!StringUtil.isEmpty(userAuditLog.getIdCardReverse())){
                    files.add(userAuditLog.getIdCardReverse());
                    userAuditLog.setIdCardReverse(null);
                }
                if(!StringUtil.isEmpty(userAuditLog.getHandIdCard())){
                    files.add(userAuditLog.getHandIdCard());
                    userAuditLog.setHandIdCard(null);
                }
            }
        }

        userAuditLog.setAuditUserId(userId);
        userAuditLogMapper.updAuditLogById(userAuditLog);

        //推送
        push.put("type", "1");
        pushMessageService.pushGeneralMessage(userAuditLog.getUserId(), push);

        //删除OSS文件
        if(files != null && files.size() > 0) {
            OSSUtil.deleteFile(aliOSSConfig, files);
        }

        return Result.returnSuccess(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result authCancelAudit(HttpServletRequest request, Integer id, String reason) throws Exception {
        HttpSession session = request.getSession(true);
        AdminUser adminUser = (AdminUser)session.getAttribute("adminUser");
        Integer userId = adminUser.getId();

        UserAuditLog userAuditLog = userAuditLogMapper.selectById(id);
        if(userAuditLog.getStatus() == 0){
            return Result.returnFailure("该记录未审核，无法撤销审核");
        }

        if(userAuditLog.getStatus() == 1) {    //撤销通过审核
            //删除主播身份
            QueryWrapper<Host> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userAuditLog.getUserId());
            hostMapper.delete(wrapper);

            //删除照片墙
            hostPhotosMapper.deleteByUserId(userAuditLog.getUserId());

            //删除头衔
            QueryWrapper<HostTitle> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("user_id", userAuditLog.getUserId());
            hostTitleMapper.delete(wrapper2);

            //收费动态改为免费
            QueryWrapper<UserDynamic> wrapper3 = new QueryWrapper<>();
            wrapper3.eq("user_id", userAuditLog.getUserId());
            wrapper3.eq("`status`", 0);
            UserDynamic userDynamic = new UserDynamic();
            userDynamic.setConfigId(0);
            userDynamicMapper.update(userDynamic, wrapper3);

            //删除招呼
            QueryWrapper<HostCallContent> wrapper4 = new QueryWrapper<>();
            wrapper4.eq("user_id", userAuditLog.getUserId());
            hostCallContentMapper.delete(wrapper4);

            //删除redis推荐库
            String key1 = "host:hot:online:";
            for(int i=3; i>=0 ; i--){
                redisTemplate.opsForZSet().remove(key1+i, userAuditLog.getUserId()+"");
            }

            //强制用户退出app
            User user = userMapper.selectById(userAuditLog.getUserId());
            String key = "token:"+user.getToken();
            redisTemplate.expire(key, -1, TimeUnit.MINUTES);
        }

        userAuditLog.setStatus(0);
        userAuditLog.setReason(userAuditLog.getReason()==null ? reason : userAuditLog.getReason()+"\n"+reason);
        userAuditLog.setAuditUserId(userId);
        userAuditLog.setAuditTime(new Date());
        userAuditLogMapper.updateById(userAuditLog);

        operationService.addOperationLog(request, "撤销审核"+ userAuditLog.getUserId()+"用户主播认证申请，理由："+reason);

        Map<String, String> push = new HashMap<>();
        push.put("title", "撤销真人认证审核");
        push.put("content", "您提交的真人认证审核已被撤销，请耐心等待重新审核，原因：" + reason);

        return Result.returnSuccess(null);
    }

    /**
     * 获取用户注册审核列表
     * @Author Shane
     * @Date 2019/10/7 21:21
     * @param
     * @return
     */
    @Override
    public Result registerList(HttpServletRequest request, Integer page, Integer limit, Integer userId, String name, String time, Integer status) throws Exception {
        Map<String, Object> data = new HashMap<>();

        if(StringUtil.isEmpty(name) && StringUtil.isEmpty(time) && userId == null && status == null){
            HttpSession session = request.getSession(true);
            List<String> userPermissions = (List<String>)session.getAttribute("userPermissions");
            if(!userPermissions.contains("/audit/register/viewList")){
                data.put("datas", new ArrayList<>());
                data.put("total", 0);

                return Result.returnSuccess(data);
            }
        }

        Date beginTime = null, endTime = null;
        if(!StringUtil.isEmpty(time)){
            String[] arr = time.split(" - ");
            beginTime = DateUtil.parse(arr[0]);
            endTime = DateUtil.parse(arr[1]);
        }

        Page<Map<String, Object>> p = new Page<>(page, limit);
        IPage<Map<String, Object>> iPage = userAuditLogMapper.registerList(p, userId, name, beginTime, endTime, status);
        data.put("datas", iPage.getRecords());
        data.put("total", iPage.getTotal());

        operationService.addOperationLog(request, "查询用户注册审核列表数据");

        return Result.returnSuccess(data);
    }

    /**
     * 用户注册审核
     * @Author Shane
     * @Date 2019/10/10 0:49
     * @param
     * @return
     */
    @Override
    @Transactional
    public Result registerAudit(HttpServletRequest request, Integer id, Integer status, Integer type, String reason) throws Exception {
        HttpSession session = request.getSession(true);
        AdminUser adminUser = (AdminUser)session.getAttribute("adminUser");
        Integer userId = adminUser.getId();

        UserAuditLog userAuditLog = userAuditLogMapper.selectById(id);
        if(userAuditLog == null){
            return Result.returnFailure("记录已不存在，无需审核");
        }
        if(userAuditLog.getStatus() != 0){
            return Result.returnFailure("该记录已经审核，不能重复审核");
        }

        //定义源文件
        List<String> files = new ArrayList<>();

        String ossUrl = "https://"+aliOSSConfig.getBucketName()+"."+aliOSSConfig.getEndpoint()+"/";

        Map<String, String> push = new HashMap<>();

        if(status == 1){    //通过
            User user = userMapper.selectById(userAuditLog.getUserId());

            if(!StringUtil.isEmpty(userAuditLog.getName())){
                user.setName(userAuditLog.getName());
            }
            if(!StringUtil.isEmpty(userAuditLog.getIcon())){
                user.setIcon(userAuditLog.getIcon());
            }

            //IM更新
            IMUtil.updateUinfo(app.getIdPrefix()+userAuditLog.getUserId(), userAuditLog.getName(), ossUrl+userAuditLog.getIcon(), null, app);

            //user更新
            userMapper.updateById(user);

            operationService.addOperationLog(request, "审核通过"+ userAuditLog.getUserId()+"用户注册更新信息的申请");

            push.put("title", "注册更新个人信息的审核通过");
            push.put("content", "您提交的注册更新个人信息的审核已经通过");

        }else if(status == 2){  //拒绝
            userAuditLog.setReason(userAuditLog.getReason()==null ? reason : userAuditLog.getReason()+"\n"+reason);

            operationService.addOperationLog(request, "审核拒绝"+ userAuditLog.getUserId()+"用户注册更新信息的申请，理由："+reason);

            push.put("title", "注册更新个人信息的审核驳回");
            push.put("content", "您提交的注册更新个人信息的审核被驳回，原因：" + reason);

            //获取源文件
            if(type == 1){
                if(!StringUtil.isEmpty(userAuditLog.getIcon())){
                    files.add(userAuditLog.getIcon());
                    userAuditLog.setIcon(null);
                }
            }
        }

        userAuditLog.setStatus(status);
        userAuditLog.setAuditUserId(userId);
        userAuditLogMapper.updAuditLogById(userAuditLog);

        //推送
        push.put("type", "1");
        pushMessageService.pushGeneralMessage(userAuditLog.getUserId(), push);

        //删除OSS文件
        if(files != null && files.size() > 0) {
            OSSUtil.deleteFile(aliOSSConfig, files);
        }

        return Result.returnSuccess(null);
    }

    @Override
    public Result registerCancelAudit(HttpServletRequest request, Integer id, String reason) throws Exception {
        HttpSession session = request.getSession(true);
        AdminUser adminUser = (AdminUser)session.getAttribute("adminUser");
        Integer userId = adminUser.getId();

        UserAuditLog userAuditLog = userAuditLogMapper.selectById(id);
        if(userAuditLog == null){
            return Result.returnFailure("记录已不存在，无法操作");
        }
        if(userAuditLog.getStatus() == 0){
            return Result.returnFailure("该记录未审核，无法撤销审核");
        }

        String ossUrl = "https://"+aliOSSConfig.getBucketName()+"."+aliOSSConfig.getEndpoint()+"/";

        Map<String, String> push = new HashMap<>();

        if(userAuditLog.getStatus() == 1){    //撤销通过审核
            User user = userMapper.selectById(userAuditLog.getUserId());

            String name = user.getName();
            if(!StringUtil.isEmpty(userAuditLog.getName())){
                name = baseMapper.getRandomUserName();
                user.setName(name);
            }

            String icon = user.getIcon();
            if(!StringUtil.isEmpty(userAuditLog.getIcon())){
                if(user.getGender() == 0){
                    icon = sysConfigMapper.getValue("default_woman_icon");
                }else{
                    icon = sysConfigMapper.getValue("default_man_icon");
                }
                user.setIcon(icon);
            }

            //IM更新
            IMUtil.updateUinfo(userAuditLog.getUserId()+"", name, ossUrl+icon, null, app);

            //user更新
            userMapper.updateById(user);
        }

        userAuditLog.setStatus(0);
        userAuditLog.setAuditUserId(userId);
        userAuditLog.setAuditTime(new Date());
        userAuditLog.setReason(userAuditLog.getReason()==null ? reason : userAuditLog.getReason()+"\n"+reason);
        userAuditLogMapper.updateById(userAuditLog);

        operationService.addOperationLog(request, "审核拒绝"+ userAuditLog.getUserId()+"用户注册更新信息的申请，理由："+reason);

        push.put("title", "撤销注册更新个人信息的审核");
        push.put("content", "您提交的注册更新个人信息的审核已被撤销，请耐心等待重新审核，原因：" + reason);
        //推送
        push.put("type", "1");
        pushMessageService.pushGeneralMessage(userAuditLog.getUserId(), push);

        return Result.returnSuccess(null);
    }

    @Override
    public Result userInfoList(HttpServletRequest request, Integer page, Integer limit, Integer userId, String item, String time, Integer status) throws Exception {
        Map<String, Object> data = new HashMap<>();

        if(StringUtil.isEmpty(time) && userId == null && status == null){
            HttpSession session = request.getSession(true);
            List<String> userPermissions = (List<String>)session.getAttribute("userPermissions");
            if(!userPermissions.contains("/audit/"+item+"/viewList")){
                data.put("userInfoAudits", new ArrayList<>());
                data.put("total", 0);

                return Result.returnSuccess(data);
            }
        }

        Date beginTime = null, endTime = null;
        if(!StringUtil.isEmpty(time)){
            String[] arr = time.split(" - ");
            beginTime = DateUtil.parse(arr[0]);
            endTime = DateUtil.parse(arr[1]);
        }

        Page<Map<String, Object>> p = new Page<>(page, limit);
        IPage<Map<String, Object>> iPage = userAuditLogMapper.queryUserInfoAuditList(p, userId, item, beginTime, endTime, status);
        List<Map<String, Object>> userInfoAudits = iPage.getRecords();
        for(Map<String, Object> userInfoAudit : userInfoAudits){
            String reason = "";
            if("potos".equals(item)) {
                //图片
                List<Map<String, Object>> potos = (List<Map<String, Object>>) JSONArray.parse(userInfoAudit.get("potos") + "");
                potos = potos == null ? new ArrayList<>() : potos;
                userInfoAudit.put("potos", potos);
            }
            if(Integer.parseInt(userInfoAudit.get("status").toString()) == 2){
                List<Map<String, Object>> auditFail = (List<Map<String, Object>>) JSONArray.parse(userInfoAudit.get("failItem") + "");
                if(auditFail != null){
                    for(Map<String, Object> map : auditFail){
                        if(item.equals(map.get("item"))){
                            reason = map.get("reason").toString();
                            break;
                        }
                    }
                }
            }
            List<Map<String, Object>> reasons = (List<Map<String, Object>>) JSONArray.parse(userInfoAudit.get("reason") + "");
            if(reasons != null){
                for(Map<String, Object> map : reasons){
                    if(item.equals(map.get("item"))){
                        reason += "\n" + map.get("reason").toString();
                    }
                }
            }
            if(reason.indexOf("\n") == 0){
                reason = reason.substring(reason.indexOf("\n")+1, reason.length());
            }
            userInfoAudit.put("reason", reason);
        }

        data.put("userInfoAudits", userInfoAudits);
        data.put("total", iPage.getTotal());

        operationService.addOperationLog(request, "查询资料更新审核列表数据");

        return Result.returnSuccess(data);
    }

    @Override
    @Transactional
    public Result userInfoAudit(HttpServletRequest request, String item, Integer id, Integer status, Integer type, String reason) throws Exception {
        HttpSession session = request.getSession(true);
        AdminUser adminUser = (AdminUser)session.getAttribute("adminUser");
        Integer userId = adminUser.getId();

        UserAuditLog userAuditLog = userAuditLogMapper.selectById(id);
        if((userAuditLog.getSuccessItem() != null && userAuditLog.getSuccessItem().contains(item))
                || (userAuditLog.getFailItem() != null && userAuditLog.getFailItem().contains(item))){
            return Result.returnFailure("该记录已经审核，不能重复审核");
        }

        Map<String, String> push = new HashMap<>();

        String auditItems = (userAuditLog.getIcon()==null?"":"icon,") + (userAuditLog.getName()==null?"":"name,")
                + (userAuditLog.getPersionSign()==null?"":"persionSign,") + (userAuditLog.getPotos()==null?"":"potos,")
                + (userAuditLog.getPotos()==null?"":"persionVideo,");
        Integer auditItemNum = auditItems.split(",").length;
        Integer successItemNum = userAuditLog.getSuccessItem() == null ? 0 : userAuditLog.getSuccessItem().split(",").length;
        Integer failItemNum = 0;
        List<Map<String, Object>> failItems = (List<Map<String, Object>>) JSONArray.parse(userAuditLog.getFailItem());
        if(failItems == null){
            failItems = new ArrayList<>();
        }else{
            failItemNum = failItems.size();
        }

        String desc = "";
        if("icon".equals(item)){
            desc = "头像";
        }else if("name".equals(item)){
            desc = "昵称";
        }else if("persion_sign".equals(item)){
            desc = "个性签名";
        }else if("potos".equals(item)){
            desc = "照片墙";
        }else if("persion_video".equals(item)){
            desc = "个性视频";
        }

        //定义源文件
        List<String> files = new ArrayList<>();

        if(status == 1){    //通过
            User user = userMapper.selectById(userAuditLog.getUserId());

            operationService.addOperationLog(request, desc+"审核通过"+userAuditLog.getUserId()+"用户资料更新申请");

            push.put("title", desc+"资料更新审核通过");
            push.put("content", "您提交的"+desc+"资料更新审核已经通过，请注意查看");

            String icon = null;
            String name = null;
            if("icon".equals(item)){
                icon = userAuditLog.getIcon();
                user.setIcon(icon);
            }else if("potos".equals(item)){
                hostPhotosMapper.deleteByUserId(userAuditLog.getUserId());

                List<Map<String, Object>> potos = (List<Map<String, Object>>) JSONArray.parse(userAuditLog.getPotos());
                for(Map<String, Object> poto : potos){
                    HostPhotos hostPhotos = new HostPhotos(userAuditLog.getUserId(), poto.get("icon")+"", Integer.parseInt(poto.get("isFirst")+""));
                    hostPhotosMapper.insert(hostPhotos);
                }
            }else if("name".equals(item)){
                name = userAuditLog.getName();
                user.setName(name);
            }else if("persion_sign".equals(item)){
                user.setPersionSign(userAuditLog.getPersionSign());
            }else if("persion_video".equals(item)){
                Host host = hostMapper.selectByUserId(userAuditLog.getUserId());
                if(host != null){
                    host.setPersionVideo(userAuditLog.getPersionVideo());
                }
                hostMapper.updateById(host);
            }

            userMapper.updateById(user);

            //IM更新
            if(icon != null || name != null) {
                String ossUrl = "https://" + aliOSSConfig.getBucketName() + "." + aliOSSConfig.getEndpoint() + "/";
                IMUtil.updateUinfo(app.getIdPrefix()+userAuditLog.getUserId(), name, icon == null ? null : ossUrl + icon, null, app);
            }

            //更新审核记录
            if(auditItemNum-successItemNum-failItemNum == 1){
                if(failItemNum != 0){
                    status = 3;
                }
            }else{
                status = 0;
            }
            userAuditLog.setStatus(status);
            userAuditLog.setSuccessItem(userAuditLog.getSuccessItem() == null ? item : userAuditLog.getSuccessItem()+","+item);

        }else if(status == 2){  //拒绝
            Map<String, Object> map = new HashMap<>();
            map.put("item", item);
            map.put("reason", reason);
            failItems.add(map);

            if(auditItemNum-successItemNum-failItemNum == 1){
                if(successItemNum != 0){
                    status = 3;
                }
            }else{
                status = 0;
            }
            userAuditLog.setStatus(status);
            userAuditLog.setFailItem(JSONArray.toJSONString(failItems));

            operationService.addOperationLog(request, desc+"审核拒绝"+ userAuditLog.getUserId()+"用户资料更新申请，理由："+reason);

            push.put("title", desc+"资料更新审核驳回");
            push.put("content", "您提交的"+desc+"资料更新审核被驳回，原因：" + reason);

            //获取源文件
            if(type == 1){
                if("icon".equals(item) && !StringUtil.isEmpty(userAuditLog.getIcon())){
                    files.add(userAuditLog.getIcon());
                    userAuditLog.setIcon(null);
                }else if("potos".equals(item)){
                    List<Map<String, Object>> potos = (List<Map<String, Object>>) JSONArray.parse(userAuditLog.getPotos());
                    if(potos != null){
                        for(Map<String, Object> poto : potos){
                            files.add(poto.get("icon")+"");
                        }
                        userAuditLog.setPotos(null);
                    }
                }else if("persion_video".equals(item) && !StringUtil.isEmpty(userAuditLog.getPersionVideo())){
                    files.add(userAuditLog.getPersionVideo());
                    userAuditLog.setPersionVideo(null);
                }
            }

        }

        userAuditLog.setAuditUserId(userId);
        userAuditLogMapper.updAuditLogById(userAuditLog);

        //推送
        push.put("type", "1");
        pushMessageService.pushGeneralMessage(userAuditLog.getUserId(), push);

        //删除OSS文件
        if(files != null && files.size() > 0) {
            OSSUtil.deleteFile(aliOSSConfig, files);
        }

        return Result.returnSuccess(null);
    }

    @Override
    public Result userInfoCancelAudit(HttpServletRequest request, Integer id, String item, String reason) throws Exception {

        HttpSession session = request.getSession(true);
        AdminUser adminUser = (AdminUser)session.getAttribute("adminUser");
        Integer userId = adminUser.getId();

        UserAuditLog userAuditLog = userAuditLogMapper.selectById(id);
        if((userAuditLog.getSuccessItem() == null || !userAuditLog.getSuccessItem().contains(item))
                && (userAuditLog.getFailItem() == null || !userAuditLog.getFailItem().contains(item))){
            return Result.returnFailure("该记录未审核，无法撤销审核");
        }

        Map<String, String> push = new HashMap<>();

        String desc = "";
        String icon = null;
        String name = null;
        User user = userMapper.selectById(userAuditLog.getUserId());
        if(userAuditLog.getSuccessItem() != null && userAuditLog.getSuccessItem().contains(item)) {
            String result = getLastUserInfoAudit(id, 1, userAuditLog.getUserId(), item);
            if("icon".equals(item)){
                desc = "头像";
                icon = result;
                if(icon == null){
                    if(user.getGender() == 0){
                        icon = sysConfigMapper.getValue("default_woman_icon");
                    }else{
                        icon = sysConfigMapper.getValue("default_man_icon");
                    }
                }
                user.setIcon(icon);
            }else if("name".equals(item)){
                desc = "昵称";
                name = result;
                if(name == null){
                    name = baseMapper.getRandomUserName();
                }
                user.setName(name);
            }else if("persion_sign".equals(item)){
                desc = "个性签名";
                user.setPersionSign(result);
            }else if("potos".equals(item)){
                desc = "照片墙";
                hostPhotosMapper.deleteByUserId(userAuditLog.getUserId());

                if(result != null){
                    List<Map<String, Object>> potos = (List<Map<String, Object>>) JSONArray.parse(result);
                    for(Map<String, Object> poto : potos){
                        HostPhotos hostPhotos = new HostPhotos(userAuditLog.getUserId(), poto.get("icon")+"", Integer.parseInt(poto.get("isFirst")+""));
                        hostPhotosMapper.insert(hostPhotos);
                    }
                }
            }else if("persion_video".equals(item)){
                desc = "个性视频";
                user.setPersionSign(result);
            }

            userMapper.updateById(user);

            //IM更新
            if(icon != null || name != null) {
                String ossUrl = "https://" + aliOSSConfig.getBucketName() + "." + aliOSSConfig.getEndpoint() + "/";
                IMUtil.updateUinfo(userAuditLog.getUserId()+"", name, icon == null ? null : ossUrl + icon, null, app);
            }

            String successItem = userAuditLog.getSuccessItem().replace(","+item, "");
            successItem = successItem.replace(item+",", "");
            successItem =successItem.replace(item, "");
            userAuditLog.setSuccessItem(successItem);
        }else{
            List<Map<String, Object>> items = new ArrayList<>();
            List<Map<String, Object>> failItems = (List<Map<String, Object>>) JSONArray.parse(userAuditLog.getFailItem());
            for(Map<String, Object> map : failItems){
                if(item.equals(map.get("item"))){
                    items.add(map);
                    break;
                }
            }
            failItems.removeAll(items);

            userAuditLog.setFailItem(JSONArray.toJSONString(failItems));
        }

        List<Map<String, Object>> reasons = (List<Map<String, Object>>) JSONArray.parse(userAuditLog.getReason());
        reasons = reasons == null ? new ArrayList<>() : reasons;
        Map<String, Object> map = new HashMap<>();
        map.put("item", item);
        map.put("reason", reason);
        reasons.add(map);

        userAuditLog.setStatus(0);
        userAuditLog.setAuditUserId(userId);
        userAuditLog.setAuditTime(new Date());
        userAuditLog.setReason(JSONArray.toJSONString(reasons));
        userAuditLogMapper.updateById(userAuditLog);

        operationService.addOperationLog(request, "撤销"+ userAuditLog.getUserId()+"用户资料更新"+desc+"审核申请，理由："+reason);

        push.put("title", "撤销"+desc+"资料更新审核");
        push.put("content", "您提交的"+desc+"资料更新审核已被撤销，请耐心等待重新审核，原因：" + reason);
        //推送
        push.put("type", "1");
        pushMessageService.pushGeneralMessage(userAuditLog.getUserId(), push);

        return Result.returnSuccess(null);
    }

    public String getLastUserInfoAudit(Integer id, Integer type, Integer userId, String item){
        String result = null;
        //获取最新资料更新审核成功记录
        UserAuditLog userInfoAuditLog = userAuditLogMapper.queryLastUserInfoAudit(id, type, userId);
        if(userInfoAuditLog == null){
            return result;
        }else{
            if(userInfoAuditLog.getSuccessItem() != null && userInfoAuditLog.getSuccessItem().contains(item)){
                if("icon".equals(item)){
                    result = userInfoAuditLog.getIcon();
                }else if("name".equals(item)){
                    result = userInfoAuditLog.getName();
                }else if("persion_sign".equals(item)){
                    result = userInfoAuditLog.getPersionSign();
                }else if("potos".equals(item)) {
                    result = userInfoAuditLog.getPotos();
                }else if("persion_video".equals(item)) {
                    result = userInfoAuditLog.getPersionVideo();
                }
            }else{
                return getLastUserInfoAudit(userInfoAuditLog.getId(), type, userId, item);
            }
        }

        return result;
    }

    @Override
    public Result getNotAuditNum(HttpServletRequest request) throws Exception {
        HttpSession session = request.getSession(true);
        List<String> userPermissions = (List<String>)session.getAttribute("userPermissions");

        Map<String, Object> data = new HashMap<>();
        List<Map<String, Object>> itemAuditList = new ArrayList<>();

        Integer auditNum = 0;
        Integer infoAuditNum = 0;
        Map<String, Object> auditMap = new HashMap<>();
        Map<String, Object> infoAuditMap = new HashMap<>();
        List<Map<String, Object>> childrenAuditList = userAuditLogMapper.queryNotAuditNum();
        for(Map<String, Object> map : childrenAuditList){
            String auditName = map.get("auditName").toString();
            if(!userPermissions.contains(auditName)){
                map.put("notAuditNum", 0);
            }
            if(Integer.parseInt(map.get("pid").toString()) == 30){
                auditNum += Integer.parseInt(map.get("notAuditNum").toString());
            }else if(Integer.parseInt(map.get("pid").toString()) == 136){
                infoAuditNum += Integer.parseInt(map.get("notAuditNum").toString());
            }
        }
        auditMap.put("id", 30);
        auditMap.put("pid", 0);
        auditMap.put("notAuditNum", auditNum);
        itemAuditList.add(auditMap);
        infoAuditMap.put("id", 136);
        infoAuditMap.put("pid", 0);
        infoAuditMap.put("notAuditNum", infoAuditNum);
        itemAuditList.add(infoAuditMap);
        itemAuditList.addAll(childrenAuditList);

        data.put("itemAuditList", itemAuditList);
        return Result.returnSuccess(data);
    }
}
